package user

import (
	models2 "github.com/crazyhl/gopermission/models"
	"github.com/gofiber/fiber/v2"
	"go-fiber-demo/models"
	"go-fiber-demo/pkg"
)

type Dto struct {
	ID          uint32
	Username    string
	Permissions []PermissionDto
}

type PermissionDto struct {
	Name        string
	Description string
}

// 获取用户信息
func LoginUserInfo(ctx *fiber.Ctx) error {
	user := ctx.Locals("loginUser").(*models.User)
	response := pkg.Response{}

	dto := new(Dto)
	dto.ID = user.ID
	dto.Username = user.Username

	for _, p := range user.FullPermissions() {
		outputPermission := PermissionDto{}
		outputPermission.Name = p.Name
		outputPermission.Description = p.Description
		dto.Permissions = append(dto.Permissions, outputPermission)
	}
	// 如果是超级管理员就返回所有的权限
	isSuperAdmin := ctx.Locals("isSuperUser")
	if isSuperAdmin == true {
		var allPermissions []models2.Permission
		db := pkg.GetConfig().GormDb
		db.Find(&allPermissions)
		dto.Permissions = nil
		for _, p := range allPermissions {
			outputPermission := PermissionDto{}
			outputPermission.Name = p.Name
			outputPermission.Description = p.Description
			dto.Permissions = append(dto.Permissions, outputPermission)
		}
	}

	response.Data = dto
	return ctx.JSON(response)
}
